package com.qk.management.web.filter;

import cn.hutool.core.util.ObjectUtil;
import com.qk.common.util.JwtUtils;
import io.jsonwebtoken.Claims;
import jakarta.servlet.*;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.util.Objects;


@WebFilter(urlPatterns = "/*")
public class LoginCheckFilter implements Filter {
    private static final String LOGIN_URL = "/login";
    private static final String TOKEN_HEADER_NAME = "token";
    private static final Logger log = LoggerFactory.getLogger(LoginCheckFilter.class);

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        String path = request.getRequestURI() ;
        boolean isLoginReq = Objects.equals(LOGIN_URL, path);
        if (isLoginReq){
            filterChain.doFilter(servletRequest,servletResponse);
            return;
        }
        String token = request.getHeader(TOKEN_HEADER_NAME);
        if (ObjectUtil.isEmpty( token)){
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            return;
        }
        try {
            Claims claims = JwtUtils.parseToken(token);
            String username = claims.get("username", String.class);
            log.info("用户{}已登录", username);
            Object id = claims.get("id");
            log.info("用户{}的id为{}", username, id);
            filterChain.doFilter(servletRequest,servletResponse);
        } catch (Exception e) {
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            return;
        }

    }
}
